//
//  WNReadScrollVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/3.
//

import UIKit

class WNReadScrollVC: WNBaseVC {
    
    lazy var readTabView: WNTableView = {
        let tab = WNTableView.init(frame: CGRect.zero, style: .plain)
        tab.delegate = self
        tab.dataSource = self
        tab.register(ReadScrollCell.self, forCellReuseIdentifier: ReadScrollCell.identifier)
        tab.backgroundColor = .clear
        return tab
    }()
    
    lazy var topView: ReadScrollTopView = {
        return ReadScrollTopView()
    }()
    
    lazy var bomView: ReadScrollBomView = {
        return ReadScrollBomView()
    }()
    
    /// 当前主控制器
    weak var mainVC: WNReadVC?
    
    /// 当前阅读章节ID列表(只会存放本次阅读的列表)
    var chapterArr: [NSNumber] = []
    /// 当前阅读的章节列表,通过已有的章节ID列表, 来获取章节模型。
    var chapterModelArr: [String: ChapterDetailModel] = [:]
    /// 是否为向上滚动
    var isScrollUp = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(topView)
        view.addSubview(bomView)
        view.addSubview(readTabView)
        topView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(StatusBarHeight+14)
        }
        bomView.snp.makeConstraints { make in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(TabBarMargin+34)
        }
        readTabView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.equalTo(0)
            make.bottom.equalTo(bomView.snp.top)
        }
    }
    
    override func dataConfig() {
        reloadProgress()
        chapterArr.append(mainVC?.recordModel?.chapterModel?.chapterId ?? NSNumber(value: 0))
        readTabView.reloadData()
        readTabView.contentOffset = CGPoint(x: 0, y: (mainVC?.recordModel?.page.intValue ?? 0)*wn_toInt(RECORD_RECT.height))
    }
    
    func reloadProgress() {
        if let m = mainVC?.recordModel {
            mainVC?.recordModel?.updateFont()
            mainVC?.navView.titleName = mainVC?.recordModel?.chapterModel?.chapterName
            mainVC?.chapterReadRequest()
            topView.darkModeConfig()
            bomView.darkModeConfig()
            topView.chapterLabel.text = ""
            bomView.chapterLabel.text = m.chapterModel?.chapterName
            bomView.pageLabel.text = "\((m.page.intValue)+1)/\(m.chapterModel?.pageCount.intValue ?? 0)"
        }
    }
}

extension WNReadScrollVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return chapterArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return getChapterModel(chapterArr[section])?.pageCount.intValue ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ReadScrollCell.identifier, for: indexPath) as! ReadScrollCell
        let chapterModel = getChapterModel(chapterArr[indexPath.section])
        cell.pageModel = chapterModel?.pageArr?[indexPath.item]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(getChapterModel(chapterArr[indexPath.section])?.pageArr?[indexPath.item].contentH.floatValue ?? 0)
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 24
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
}

extension WNReadScrollVC {
    /// 预加载上一个章节
    func preloadingPrev(_ chapterModel: ChapterDetailModel?) {
        if let model = chapterModel, model.chapterPrevId != -1 {
            let prevId = model.chapterPrevId
            WNThread.wn_runInNewThread { [weak self] in
                if SNKeyedArchiver.isExist(model.bookId, prevId.stringValue) {
                    let cModel = SNKeyedArchiver.unarchiver(model.bookId, prevId.stringValue) as? ChapterDetailModel
                    self?.chapterModelArr[prevId.stringValue] = cModel
                    cModel?.updateFont()
                    WNThread.wn_runInMainThread {
                        self?.handerPreloadingModel(cModel, prevId, -1)
                    }
                }else {
                    WNThread.wn_runInMainThread {
                        self?.mainVC?.handleChooseChapter(prevId)
                    }
                }
            }
        }
    }
    
    /// 预加载下一个章节
    func preloadingNext(_ chapterModel: ChapterDetailModel?) {
        if let model = chapterModel, model.chapterNextId != -1 {
            let nextId = model.chapterNextId
            WNThread.wn_runInNewThread { [weak self] in
                var cModel: ChapterDetailModel?
                if SNKeyedArchiver.isExist(model.bookId, nextId.stringValue) {
                    cModel = SNKeyedArchiver.unarchiver(model.bookId, nextId.stringValue) as? ChapterDetailModel
                    cModel?.updateFont()
                    WNThread.wn_runInMainThread {
                        self?.handerPreloadingModel(cModel, -1, nextId)
                    }
                }else {
                    WNThread.wn_runInMainThread {
                        self?.mainVC?.handleChooseChapter(nextId)
                    }
                }
            }
        }
    }
    
    /// 处理预加载
    func handerPreloadingModel(_ model: ChapterDetailModel?, _ prevId: NSNumber, _ nextId: NSNumber) {
        if let m = model {
            if nextId == -1 {
                // 加入阅读内容列表
                chapterModelArr[prevId.stringValue] = m
                // 当前章节索引
                let prevIndex = max(0, ((chapterArr.firstIndex(of: m.chapterNextId) ?? 0)-1))
                // 阅读章节ID列表加入
                if chapterArr.wn_contains(obj: prevId) {
                    chapterArr.wn_remove(prevId, isRepeat: true)
                }
                chapterArr.insert(prevId, at: prevIndex)
                // 刷新
                readTabView.reloadData()
                // 定位
                readTabView.contentOffset = CGPoint(x: 0, y: readTabView.contentOffset.y+m.pageTotalHeight)
            }else if prevId == -1 {
                // 加入阅读内容列表
                chapterModelArr[nextId.stringValue] = m
                // 当前章节索引
                let nextIndex = (chapterArr.firstIndex(of: m.chapterPrevId) ?? 0)+1
                // 阅读章节ID列表加入
                if !chapterArr.wn_contains(obj: nextId) {
                    chapterArr.insert(nextId, at: nextIndex)
                    // 刷新
                    readTabView.beginUpdates()
                    readTabView.insertSections(IndexSet(integer: nextIndex) , with: .top)
                    readTabView.endUpdates()
                }
            }
        }
    }
    
    /// 获取章节内容模型
    func getChapterModel(_ chapterId: NSNumber) -> ChapterDetailModel? {
        var chapterModel: ChapterDetailModel?
        if chapterModelArr.keys.contains(chapterId.stringValue) { // 存在章节内容
            chapterModel = chapterModelArr[chapterId.stringValue]
        }else { // 不存在章节列表
            let bookId = mainVC?.bookDetailModel?.bookId
            if SNKeyedArchiver.isExist(bookId, chapterId.stringValue) {
                let chapterModel = SNKeyedArchiver.unarchiver(bookId, chapterId.stringValue) as? ChapterDetailModel
                chapterModel?.updateFont()
                chapterModelArr[chapterId.stringValue] = chapterModel
            }
        }
        return chapterModel
    }
}

extension WNReadScrollVC: UIScrollViewDelegate {
    // 结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewDidEndDecelerating(scrollView)
        }
    }
    
    // 结束减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        isScrollUp = scrollView.contentOffset.y > 0
        updateReadRecord(isScrollUp, true)
    }
    
    /// 更新阅读记录(滚动模式) isRollingUp:是否为往上滚动
    func updateReadRecord(_ isRollingUp: Bool, _ request: Bool = false) {
        if let indexPaths = readTabView.indexPathsForVisibleRows, !indexPaths.isEmpty {
            WNThread.wn_runInNewThread { [weak self] in
                let indexPath: IndexPath = (isRollingUp ? indexPaths.last : indexPaths.first)!
                let chapterModel = self?.getChapterModel(self?.chapterArr[indexPath.section] ?? 0)
                self?.mainVC?.recordModel?.modify(model: chapterModel, toPage: indexPath.row)
                READ_RECORD_CURRENT_CHAPTER_LOCATION = self?.mainVC?.recordModel?.locationFirst?.intValue ?? 0
                WNThread.wn_runInMainThread {
                    self?.reloadProgress()
                    if request {
                        if isRollingUp {
                            if self?.mainVC?.recordModel?.page.intValue == ((self?.mainVC?.recordModel?.chapterModel?.pageCount.intValue ?? 1)-1) {
                                self?.mainVC?.chapterReadComplete(self?.mainVC?.recordModel?.chapterModel?.chapterId.intValue ?? 0, self?.mainVC?.recordModel?.chapterModel?.chapterName ?? "")
                                if self?.mainVC?.recordModel?.chapterModel?.chapterNextId.intValue == -1 {
                                    self?.mainVC?.chapterReadComplete()
                                }
                                self?.preloadingNext(chapterModel)
                            }
                        }else {
                            if self?.mainVC?.recordModel?.page.intValue == 0 {
                                self?.preloadingPrev(chapterModel)
                            }
                        }
                    }
                }
            }
        }
    }
}
